package pers.cj.pdos.controller.other;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.BusinessSet;
import pers.cj.pdos.entity.Company;
import pers.cj.pdos.entity.Sale;
import pers.cj.pdos.excel.ExcelHouseQuery;
import pers.cj.pdos.excel.ExcelMoneyWater;
import pers.cj.pdos.service.*;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.DateUtils;
import pers.cj.pdos.utils.FileProperUtil;
import pers.cj.pdos.utils.PdosUtils;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.vo.SaleVo;
import pers.cj.pdos.vo.UserVo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 库存查询
 */
@Controller
@RequestMapping("/funds")
public class MoneyWaterController extends BaseController {
    @Autowired
    IMoneyWaterService moneyWaterService;
    @Autowired
    ISettAccountService settAccountService;
    @Autowired
    IGoodsStockService goodsStockService;
    @Autowired
    IArrearsWaitService arrearsWaitService;
    @Autowired
    IPayWaitService payWaitService;

    @RequiresPermissions("moneyWater:query")
    @RequestMapping("/moneyWater")
    public String saleTicket(Model model, String date1, String date2){
        model.addAttribute("date1",date1);
        model.addAttribute("date2",date2);
        return "funds/moneyWater";
    }

    /**
     * 获取资产情况
     * @return
     */
    @ResponseBody
    @RequestMapping("/moneyWater/getProperty")
    public ResponseData getProperty() {
        Company company = getCompany();
        BigDecimal balance = settAccountService.getTotalBalance(company.getId());
        BigDecimal houseAmt = goodsStockService.getTotalStockAmount(company.getId(),null,null);
        BigDecimal arrearsWait = arrearsWaitService.getTotalAmount(company.getId());
        BigDecimal payWait = payWaitService.getTotalAmount(company.getId());
        BigDecimal total = balance.add(houseAmt).add(arrearsWait).subtract(payWait);

        Map map = new HashMap();
        map.put("balance", balance);
        map.put("houseAmt",houseAmt);
        map.put("arrearsWait", arrearsWait);
        map.put("payWait", payWait);
        map.put("total", total);
        return ResponseData.success(map);
    }

    /**
     * 获取近7日趋势数据
     * @return
     */
    @ResponseBody
    @RequestMapping("/moneyWater/getWeekTrend")
    public ResponseData getWeekTrend(String userId,String day) {
        Company company = getCompany();
        BusinessSet businessSet = getBusinessSet();
        UserVo userVo = getLoginUserVo();
        Date date2 = DateUtils.genDate(day, DateUtils.YYYY_MM_DD);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date2);
        calendar.add(Calendar.DATE, -6);
        Date date1 = calendar.getTime();

        // 先准备好初始数据
        Map<String, BigDecimal> tempMap = new HashMap<>();
        tempMap.put("inAmt", new BigDecimal(0));
        tempMap.put("outAmt", new BigDecimal(0));
        Map<String, Object> chatMap = new LinkedHashMap<>();
        for (int i=0;i<7;i++) {
            chatMap.put(calendar.get(Calendar.DAY_OF_MONTH)+"日", tempMap);
            calendar.add(Calendar.DATE, 1);
        }

        List<Map> mapList = moneyWaterService.listTotalGroupByDate(company.getId(), PdosUtils.getViewOtherStoreId(userVo,null),userId,date1,date2);
        if (mapList!=null) {
            for (Map map : mapList) {
                chatMap.put(map.get("date")+"日", map);
            }
        }

        List<String> labels = new ArrayList<>();
        labels.add("收入");
        labels.add("支出");

        List<String> xData = new ArrayList<>();
        List<Object> inList = new ArrayList<>();
        List<Object> outList = new ArrayList<>();

        BigDecimal zero = new BigDecimal(0);
        for (Map.Entry<String, Object> entry : chatMap.entrySet()) {
            xData.add(entry.getKey());
            if (entry.getValue() instanceof Map) {
                String inAmt = ((Map) entry.getValue()).get("inAmt") + "";
                String outAmt = ((Map) entry.getValue()).get("outAmt") + "";
                inList.add(Utils.getFloatStr(inAmt,businessSet.getPricePoint()));
                outList.add(Utils.getFloatStr(outAmt,businessSet.getPricePoint()));
            } else {
                inList.add(zero);
                outList.add(zero);
            }
        }

        List<Map> series = new ArrayList<>();
        Map<String, Object> inMap = new HashMap<>();
        inMap.put("name","收入");
        inMap.put("type","line");
        inMap.put("data",inList);
        series.add(inMap);

        Map<String, Object> outMap = new HashMap<>();
        outMap.put("name","支出");
        outMap.put("type","line");
        outMap.put("data",outList);
        series.add(outMap);

        Map<String, Object> map = new HashMap<>();
        map.put("labels",labels);
        map.put("xData",xData);
        map.put("series",series);

        return ResponseData.success(map);
    }

    @ResponseBody
    @RequiresPermissions("moneyWater:query")
    @RequestMapping("/moneyWater/getList")
    public ResponseList getList(int page,
                                int limit,
                                String close,
                                String search,
                                String no,
                                String unitName,
                                String userId,
                                String settAccountId,
                                String type,
                                String typeProject,
                                String date1,
                                String date2,
                                String storeId){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<Map> list = moneyWaterService.listVo(company.getId(),
                page,
                limit,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(unitName),
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                settAccountId,
                Utils.genInteger(type),
                Utils.genInteger(typeProject),
                Utils.genDate(date1),
                Utils.genDate(date2),
                storeId);
        long count = moneyWaterService.count(company.getId(),
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(unitName),
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                settAccountId,
                Utils.genInteger(type),
                Utils.genInteger(typeProject),
                Utils.genDate(date1),
                Utils.genDate(date2),
                storeId);
        return ResponseList.success(count,list);
    }

    @ResponseBody
    @RequiresPermissions("moneyWater:export")
    @RequestMapping("/moneyWater/export")
    public ResponseData export(String close,
                               String search,
                               String no,
                               String unitName,
                               String userId,
                               String settAccountId,
                               String type,
                               String typeProject,
                               String date1,
                               String date2,
                               String storeId) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<Map> list = moneyWaterService.listVo(company.getId(),
                null,
                null,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(unitName),
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                settAccountId,
                Utils.genInteger(type),
                Utils.genInteger(typeProject),
                Utils.genDate(date1),
                Utils.genDate(date2),
                storeId);

        String fileName = "资金流水列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelMoneyWater.class);
            sheet1.setSheetName("资金流水列表信息");
            writer.write(genExcelList(list), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("订单列表导出失败");
        }
    }

    private List<ExcelMoneyWater> genExcelList(List<Map> mapList) {
        List<ExcelMoneyWater> list = new ArrayList<>();

        for (Map map : mapList) {
            ExcelMoneyWater excel = new ExcelMoneyWater();
            excel.setDate(PdosUtils.genDateFromMap(map,"date"));
            excel.setNo((String) map.get("no"));
            excel.setStore((String) map.get("store"));
            excel.setUnitName((String) map.get("unitName"));

            excel.setTypeName((String) map.get("typeName"));
            excel.setUser((String) map.get("user"));
            excel.setSettAccount((String) map.get("settAccount"));
            excel.setInAmt(map.get("inAmt").toString());
            excel.setOutAmt(map.get("outAmt").toString());
            excel.setRemark((String) map.get("remark"));
            excel.setStatus((Integer)map.get("close")==1 ? "作废":"");

            list.add(excel);
        }
        return list;
    }
}
